package top.yuan67.demo;

import cloud.tianai.captcha.generator.common.model.dto.ImageCaptchaInfo;
import cloud.tianai.captcha.validator.common.model.dto.ImageCaptchaTrack;
import cloud.tianai.captcha.validator.impl.BasicCaptchaTrackValidator;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static top.yuan67.demo.AjaxResult.error;
import static top.yuan67.demo.AjaxResult.success;

/**
 * 验证码操作处理
 */
@RestController
public class CaptchaController {
  private static final Logger log = LoggerFactory.getLogger(CaptchaController.class);
  
  @Resource
  private CaptchaUtils captchaUtils;
  
  @Resource
  private RedisCache redisCache;
  
  /**
   * 生成验证码
   */
  @GetMapping("/captchaImage")
  public AjaxResult getCode(String username) {
    if(StringUtils.isEmpty(username)){
      return null;
    }
  
    AjaxResult ajax = success();
    
    String uuid = UUID.randomUUID().toString();
    String base64 = Base64.encode(username.getBytes());
  
    ImageCaptchaInfo response = captchaUtils.genCaptcha(base64, uuid);
    ajax.put("id", base64);
    ajax.put("captcha", response);
    return ajax;
  }
  
  @PostMapping("/check")
  public AjaxResult checkCaptcha(@RequestBody ImageCaptchaTrack imageCaptchaTrack) {
    BasicCaptchaTrackValidator sliderCaptchaValidator = new BasicCaptchaTrackValidator();
    sliderCaptchaValidator.checkParam(imageCaptchaTrack);
    String key = Constants.CAPTCHA_CODE_KEY + imageCaptchaTrack.getData();
    /*boolean b = redisCache.hasKey(key);
    if(!b){
      return error(501, "验证码已过期");
    }*/
    try {
      Map<String, Object> map = redisCache.getCacheObject(key);
      boolean check = sliderCaptchaValidator.valid(imageCaptchaTrack, map).isSuccess();
  
      if (check) {
        String uuid = map.get(Constants.UUID).toString();
        redisCache.setCacheObject(key, uuid, 30, TimeUnit.SECONDS);
        return success(uuid);
      }
//      redisCache.setCacheObject("captcha_error",);
      return error(501, "验证码错误");
    }catch (Exception e){
      log.warn("这里类型转化异常可能是用户拿着之前的验证码来做验证了，刷新验证码就好了：{}", e);
      return error(501, "验证码错误");
    }
  }
  
}
